<template>
  <div class="ai-chat-container">
    <!-- 聊天窗口 -->
    <div class="chat-window">
      <!-- 聊天消息区域 -->
      <div class="chat-messages" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.type]"
        >
          <div class="message-avatar">
            <el-avatar 
              :size="40" 
              :src="message.type === 'user' ? userAvatar : aiAvatar"
              :style="{ backgroundColor: message.type === 'user' ? '#409EFF' : '#67C23A' }"
            >
              {{ message.type === 'user' ? '我' : 'AI' }}
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="message-bubble">
              <div class="message-text">
                <!-- 流式响应显示 -->
              <span v-if="message.isStreaming && message.type === 'ai'" class="streaming-text">
                {{ message.content }}
              </span>
              <span v-else-if="message.type === 'ai'">
                {{ message.content }}
              </span>
              <span v-else>
                {{ message.content }}
              </span>
              </div>
              <div class="message-time">{{ message.time }}</div>
            </div>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="isLoading" class="message ai">
          <div class="message-avatar">
            <el-avatar size="40" style="background-color: #67C23A;">AI</el-avatar>
          </div>
          <div class="message-content">
            <div class="message-bubble">
              <div class="message-text">
                <el-icon class="is-loading"><Loading /></el-icon>
                AI正在思考中...
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input-area">
        <div class="input-container">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题..."
            @keydown.enter="handleSendMessage"
            resize="none"
          />
          <div class="input-actions">
            <el-button 
              type="primary" 
              :loading="isLoading"
              @click="handleSendMessage"
              :disabled="!inputMessage.trim()"
            >
              发送
            </el-button>
            <el-button @click="clearMessages">清空</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import axios from 'axios'

// 消息接口定义
interface ChatMessage {
  type: 'user' | 'ai'
  content: string
  time: string
  isStreaming?: boolean // 是否为流式响应
}

// 响应数据
const inputMessage = ref('')
const isLoading = ref(false)
const messagesContainer = ref<HTMLElement>()

// 头像URL（可以使用默认头像）
const userAvatar = ref('')
const aiAvatar = ref('')

// 消息列表
const messages = reactive<ChatMessage[]>([])

// 格式化时间
const formatTime = (date: Date = new Date()) => {
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 发送消息
const handleSendMessage = async () => {
  const message = inputMessage.value.trim()
  if (!message) return

  // 添加用户消息
  const userMessage: ChatMessage = {
    type: 'user',
    content: message,
    time: formatTime()
  }
  messages.push(userMessage)
  
  // 清空输入框
  inputMessage.value = ''
  
  // 滚动到底部
  await scrollToBottom()
  
  // 设置加载状态
  isLoading.value = true
  
  try {
    // 创建AI消息（流式响应）
    const aiMessage: ChatMessage = {
      type: 'ai',
      content: '',
      time: formatTime(),
      isStreaming: true
    }
    messages.push(aiMessage)
    
    // 使用Fetch API进行流式响应
    const response = await fetch(`http://localhost:8012/persistent2?msg=${encodeURIComponent(message)}&userId=1101`)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    // 后端返回的是SSE格式，但格式不规范 - 每个data:字段只包含1-2个字符
    // 使用流式读取器处理SSE响应
    const reader = response.body?.getReader()
    if (!reader) {
      throw new Error('无法获取响应流')
    }
    
    const decoder = new TextDecoder('utf-8')
    let buffer = ''
    
    try {
      // 读取流数据
      while (true) {
        const { done, value } = await reader.read()
        
        if (done) {
          console.log('SSE流结束')
          break
        }
        
        // 解码数据并处理缓冲区
        buffer += decoder.decode(value, { stream: true })
        
        // 处理缓冲区中的完整行
        let newlineIndex
        while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
          const line = buffer.slice(0, newlineIndex).trim()
          buffer = buffer.slice(newlineIndex + 1)
          
          // 处理data字段（支持不规范的格式）
          if (line.startsWith('data:')) {
            // 提取data字段的内容，去除前后的空格
            const content = line.slice(5).trim()
            
            if (content && content !== '[DONE]') {
              console.log('收到SSE数据块:', content)
              
              // 后端已经做了逐字分割，直接显示内容
              // 但需要过滤掉多余的data:前缀和空格
              const cleanContent = content.replace(/^data:\s*/, '').trim()
              
              if (cleanContent && cleanContent !== '[DONE]') {
                // 后端返回的是词语级别的流式数据（每个data字段包含1-3个词语）
                // 为了确保流式效果明显可见，我们将词语拆分成单个字符显示
                const characters = cleanContent.split('')
                
                for (const char of characters) {
                  // 逐个字符添加到消息内容
                  aiMessage.content += char
                  
                  // 强制Vue响应式更新 - 使用Object.assign触发深度更新
                  messages.splice(messages.length - 1, 1, { ...aiMessage })
                  
                  // 强制DOM更新
                  await nextTick()
                  
                  // 滚动到底部
                  await scrollToBottom()
                  
                  // 设置明显的延迟，确保流式效果可见
                  await new Promise(resolve => setTimeout(resolve, 80))
                }
                
                // 词语之间添加额外延迟
                await new Promise(resolve => setTimeout(resolve, 120))
              }
            }
          }
        }
      }
    } finally {
      reader.releaseLock()
    }
    
    // 流式响应完成，标记为非流式状态
    aiMessage.isStreaming = false
    
  } catch (error) {
    console.error('调用AI接口失败:', error)
    ElMessage.error('AI服务暂时不可用，请稍后重试')
    
    // 移除流式消息并添加错误提示
    if (messages.length > 0 && messages[messages.length - 1].isStreaming) {
      messages.pop()
    }
    
    // 添加错误提示消息
    const errorMessage: ChatMessage = {
      type: 'ai',
      content: '抱歉，AI服务暂时不可用，请检查后端服务是否正常运行。',
      time: formatTime()
    }
    messages.push(errorMessage)
  } finally {
    isLoading.value = false
    await scrollToBottom()
  }
}

// 清空消息
const clearMessages = () => {
  messages.length = 0
  ElMessage.success('聊天记录已清空')
}

// 组件挂载时添加欢迎消息
onMounted(() => {
  const welcomeMessage: ChatMessage = {
    type: 'ai',
    content: '您好！我是AI助手，很高兴为您服务。请问有什么可以帮助您的吗？',
    time: formatTime()
  }
  messages.push(welcomeMessage)
  scrollToBottom()
})
</script>

<style scoped>
.ai-chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  max-height: calc(100vh - 200px);
}

.message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 10px;
}

.message-content {
  max-width: 60%;
}

.message-bubble {
  background: #f0f0f0;
  padding: 12px 16px;
  border-radius: 8px;
  position: relative;
}

.message.user .message-bubble {
  background: #409EFF;
  color: #fff;
}

.message.ai .message-bubble {
  background: #f0f0f0;
  color: #333;
}

.message-text {
  margin-bottom: 5px;
  line-height: 1.5;
  word-wrap: break-word;
}

/* 流式文本样式 - 最基础 */
.streaming-text {
  /* 只保留最基础的流式效果，无任何额外样式 */
}

/* 流式光标样式 - 已移除 */
/* .streaming-cursor {
  animation: blink 0.6s infinite;
  color: #409EFF;
  font-weight: bold;
  margin-left: 2px;
  font-size: 1.2em;
  vertical-align: middle;
  text-shadow: 0 0 8px rgba(64, 158, 255, 0.8);
} */

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

@keyframes typewriter {
  from {
    opacity: 0.3;
    transform: translateY(3px) scale(0.98);
    filter: blur(0.5px);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
    filter: blur(0);
  }
}

/* 流式消息气泡的特殊样式 - 已移除 */
/* .message.ai .message-bubble .streaming-text {
  border-left: 3px solid #409EFF;
  padding-left: 8px;
  margin-left: -8px;
  background: linear-gradient(90deg, rgba(64, 158, 255, 0.1) 0%, rgba(103, 194, 58, 0.1) 100%);
  border-radius: 4px;
} */

/* 流式文本的逐字动画效果 */
.streaming-text span {
  display: inline-block;
  animation: charPop 0.1s ease-out;
}

@keyframes charPop {
  0% {
    opacity: 0;
    transform: translateY(5px) scale(0.8);
  }
  100% {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.message-time {
  font-size: 12px;
  color: #999;
  text-align: right;
}

.message.user .message-time {
  color: rgba(255, 255, 255, 0.8);
}

.chat-input-area {
  border-top: 1px solid #e6e6e6;
  padding: 20px;
  background: #fff;
}

.input-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.is-loading {
  animation: rotating 2s linear infinite;
  margin-right: 8px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>